from django.shortcuts import render
from django.http import HttpResponse, JsonResponse, QueryDict
from utils.auth import login_required, conn_k8s_api
from utils.dateformat import dt_format
from kubernetes import client
import time


# Create your views here.


@login_required
def service(request):
    return render(request, "balance/service.html")


@login_required
def svc_tabledata(request):
    auth_type = request.session.get("auth_type", False)
    namespace_val = request.GET.get("namespace")
    conn_k8s_api(request, auth_type=auth_type)
    core_api = client.CoreV1Api()
    if request.method == "GET":
        svc_list = []
        try:
            for svc in core_api.list_namespaced_service(namespace_val).items:
                name = svc.metadata.name
                namespace = svc.metadata.namespace
                labels = svc.metadata.labels
                type = svc.spec.type
                cluster_ip = svc.spec.cluster_ip
                port_list = []
                for p in svc.spec.ports:  # 不是序列，不能直接返回
                    port_name = p.name
                    port = p.port
                    target_port = p.target_port
                    protocol = p.protocol
                    node_port = ""
                    if type == "NodePort":
                        node_port = p.node_port
                    p = {'port_name': port_name, 'port': port, 'protocol': protocol, 'target_port': target_port,
                         'node_port': node_port}
                    port_list.append(p)
                selector = svc.spec.selector
                create_time = svc.metadata.creation_timestamp
                create_time = dt_format(create_time)
                # 确认是否关联Pod
                endpoint = ""
                for ep in core_api.list_namespaced_endpoints(namespace_val).items:
                    if ep.metadata.name == name and ep.subsets is None:
                        endpoint = "未关联"
                    else:
                        endpoint = "已关联"

                svc = {"name": name, "namespace": namespace, "type": type,
                       "cluster_ip": cluster_ip, "ports": port_list, "labels": labels,
                       "selector": selector, "endpoint": endpoint, "create_time": create_time}
                search_key = request.GET.get("key", None)
                if search_key:
                    if search_key in name:  # in 则为模糊查询
                        svc_list.append(svc)
                else:
                    svc_list.append(svc)
            count = len(svc_list)
            page = int(request.GET.get("page"))
            limit = int(request.GET.get("limit"))
            start = (page - 1) * limit
            end = page * limit
            svc_list = svc_list[start:end]
            code = 0
            msg = "service获取成功！"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "无权限！"
            else:
                msg = "查询失败！"
            code = 1
        return JsonResponse({"code": code, "data": svc_list, "msg": msg, "count": count})
    elif request.method == "DELETE":
        del_data = QueryDict(request.body)
        try:
            name = del_data.get('name')
            namespace = del_data.get('namespace')
            core_api.delete_namespaced_service(namespace=namespace, name=name)
            while True:
                name_list = []
                for svc in core_api.list_namespaced_service(namespace=namespace).items:
                    name_list.append(svc.metadata.name)
                if name not in name_list:
                    break
                else:
                    time.sleep(1)  # 调用k8s接口删除，需要等待k8s响应
            code = 0
            msg = "删除数据成功！"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "无权限！"
            else:
                msg = "删除失败！"
            code = 1
        data = {'code': code, 'msg': msg}
        return JsonResponse(data)


@login_required
def ingress(request):
    return render(request, "balance/ingress.html")


@login_required
def ing_tabledata(request):
    auth_type = request.session.get("auth_type", False)
    namespace_val = request.GET.get("namespace")
    conn_k8s_api(request, auth_type=auth_type)
    networking_api = client.NetworkingV1Api()
    if request.method == "GET":
        ing_list = []
        try:
            for ing in networking_api.list_namespaced_ingress(namespace_val).items:
                name = ing.metadata.name
                namespace = ing.metadata.namespace
                labels = ing.metadata.labels
                service = "None"
                http_hosts = "None"
                for h in ing.spec.rules:
                    host = h.host
                    path = ("/" if h.http.paths[0].path is None else h.http.paths[0].path)
                    service_name = h.http.paths[0].backend.service.name
                    service_port = h.http.paths[0].backend.service.port.number
                    http_hosts = {'host': host, 'path': path, 'service_name': service_name,
                                  'service_port': service_port}

                https_hosts = "None"
                if ing.spec.tls is None:
                    https_hosts = ing.spec.tls
                else:
                    for tls in ing.spec.tls:
                        host = tls.hosts[0]
                        secret_name = tls.secret_name
                        https_hosts = {'host': host, 'secret_name': secret_name}

                create_time = ing.metadata.creation_timestamp
                create_time = dt_format(create_time)
                ing = {"name": name, "namespace": namespace, "labels": labels, "http_hosts": http_hosts,
                       "https_hosts": https_hosts, "service": service, "create_time": create_time}
                search_key = request.GET.get("key", None)
                if search_key:
                    if search_key in name:  # in 则为模糊查询
                        ing_list.append(ing)
                else:
                    ing_list.append(ing)
            count = len(ing_list)
            page = int(request.GET.get("page"))
            limit = int(request.GET.get("limit"))
            start = (page - 1) * limit
            end = page * limit
            ing_list = ing_list[start:end]
            code = 0
            msg = "ingress获取成功！"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "无权限！"
            else:
                msg = "查询失败！"
            code = 1
        return JsonResponse({"code": code, "data": ing_list, "msg": msg, "count": count})
    elif request.method == "DELETE":
        del_data = QueryDict(request.body)
        try:
            name = del_data.get('name')
            namespace = del_data.get('namespace')
            networking_api.delete_namespaced_ingress(namespace=namespace, name=name)
            while True:
                name_list = []
                for ing in networking_api.list_namespaced_ingress(namespace).items:
                    name_list.append(ing.metadata.name)
                if name not in name_list:
                    break
                else:
                    time.sleep(1)  # 调用k8s接口删除，需要等待k8s响应
            code = 0
            msg = "删除数据成功！"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "无权限！"
            else:
                msg = "删除失败！"
            code = 1
        data = {'code': code, 'msg': msg}
        return JsonResponse(data)
